package me.biezhi.longweibo.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class ConvertUtil {

	public static Integer MIN_WIDTH = 300;
	public static Integer MIN_HEIGHT = 450;
	
	private static final String classPath = ConvertUtil.class.getResource("/").getFile();
	
	public static boolean exec(String url, String imgPath){
		url = url.startsWith("http://") ? url : "http://" + url; 
		while(covertImg(url, imgPath)){
			return true;
		}
		return false;
	}
	
	public static void writeHtml(String rootpath, String fileNmae, String html){
		File writename = new File(rootpath + File.separator + "html" + File.separator + fileNmae);
		try {
			writename.createNewFile(); // 创建新文件
			BufferedWriter out = new BufferedWriter(new FileWriter(writename));
			out.write(html);
			out.flush();
			out.close();
		} catch (IOException e) {
			System.out.println("写入html失败");
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除文件
	 * @param string
	 */
	public static void removeHtml(String fileName) {
		File file = new File(fileName);
		if(file.exists() && file.isFile()){
			file.delete();
		}
	}
	
	private static boolean covertImg(final String url, final String imgPath){
		final String cmd = " --url=" + url + " --out=" + imgPath;
		Process proc = null;
		final String options = " --min-width=" + MIN_WIDTH + " --min-height=" + MIN_HEIGHT;
		// 执行一个exe文件
		try {
			proc = Runtime.getRuntime().exec(classPath + "CutyCapt.exe" + cmd + options);
			proc.waitFor();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return false;
	}
}
